package com.plian.system.controller.pm.investmentuprecord;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pm.investmentuprecord.InvestmentupRecord;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.pm.appraisalreportback.IAppraisalReportBackService;
import com.plian.system.service.pm.investmentuprecord.IInvestmentupRecordService;
import com.plian.system.service.pm.ownershipstructureback.IOwnershipStructureBackService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.investmentuprecord.InvestmentupRecordVO;
import com.plian.system.wrapper.pm.investmentuprecord.InvestmentupRecordWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import liquibase.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 增资扩股交易备案主表 控制器
 *
 * @author gangan
 * @since 2019-10-18
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/investmentuprecord")
@Api(value = "增资扩股交易备案主表 控制器", tags = "增资扩股交易备案主表接口")
public class InvestmentupRecordController extends BaseController {

    private IInvestmentupRecordService investmentupRecordService;
    private IOwnershipStructureBackService ownershipStructureBackService;
    private IAppraisalReportBackService appraisalReportBackService;
    private FileService fileService;
    private FormWorkflowService formWorkflowService;

    private InvestmentupRecordWrapper investmentupRecordWrapper;

    /**
     * 详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "详情", notes = "传入investmentupRecord")
    public R<InvestmentupRecordVO> detail(@Valid @RequestBody InvestmentupRecord investmentupRecord) {
        InvestmentupRecordVO investmentupRecordVO = investmentupRecordWrapper.entityToVO(investmentupRecordService.getOne(Condition.getQueryWrapper(investmentupRecord)));
        return investmentupRecordService.getDetailObj(investmentupRecordVO);
    }

    /**
     * 分页 增资扩股交易备案主表
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页", notes = "传入query")
    public ListResult<InvestmentupRecordVO> list(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }

        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<InvestmentupRecord> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new InvestmentupRecord()), entityList
        );
        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());
        IPage<InvestmentupRecord> pages = investmentupRecordService.page(Condition.getPage(query), queryWrapper);
        List<InvestmentupRecordVO> investmentupRecordVOS = investmentupRecordWrapper.entityToVO(pages.getRecords());
        ListResult<InvestmentupRecordVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(investmentupRecordVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }


    /**
     * 新增或修改 增资扩股交易备案主表
     */
    @PostMapping("/submit")
    @LogOperation("增资扩股交易备案-提交")
    @ApiOperation(value = "新增或修改", notes = "传入investmentupRecordVO")
    public R submit(@Valid @RequestBody InvestmentupRecordVO investmentupRecordVO) {
        Boolean checkResult = false;

        if (!(Optional.ofNullable(investmentupRecordVO.getStatus()).isPresent() && investmentupRecordVO.getStatus() == FormStatusConstant.STASH)) {
            checkResult = investmentupRecordService.checkIsExisted(investmentupRecordVO.getId(), investmentupRecordVO.getCode());
        }

        if (checkResult) {
            if (StringUtil.isBlank(investmentupRecordVO.getVersion())) {
                investmentupRecordVO.setVersion("1");
            }

            if (Optional.ofNullable(investmentupRecordVO.getStatus()).isPresent() && investmentupRecordVO.getStatus() != FormStatusConstant.STASH) {
                investmentupRecordVO.setFormType(String.valueOf(FormTypeConstant.CQZC_INVESTMENTU_PRECORD));
            }
            InvestmentupRecord investmentupRecord = new InvestmentupRecord();
            BeanUtils.copyProperties(investmentupRecordVO, investmentupRecord);
            boolean result = investmentupRecordService.saveOrUpdate(investmentupRecord);
            if (result) {
                investmentupRecordVO.setId(investmentupRecord.getId());
                investmentupRecordService.saveChild(investmentupRecordVO);
                List<HashMap> listDoc = investmentupRecordVO.getList_doc();
                fileService.edit(investmentupRecord.getId().toString(), listDoc);
//				fileService.saveAll(investmentupRecord.getId().toString(),listDoc);
            }

            HashMap<String, Object> processVariable = new HashMap<>();
            formWorkflowService.startProcessAndSimulate(String.valueOf(investmentupRecordVO.getId()), investmentupRecordVO.getFormType(), processVariable);

            return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
        } else {
            return new R(CommonCode.FAIL);
        }
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @LogOperation("增资扩股交易备案-删除")
    @ApiOperation(value = "删除", notes = "传入pd")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return investmentupRecordService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA))) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 分页
     */
    @PostMapping("/reportList")
    @ApiOperation(value = "分页", notes = "传入pd")
    public ListResult<PageData> reportList(@RequestBody PageData pd) {
        return investmentupRecordService.reportList(pd);
    }


    /**
     * 打印
     */
    @GetMapping("/buildpdf/{id}")
    @ApiOperation(value = "打印", notes = "传入id")
//	@PassToken
    public ResponseEntity<FileSystemResource> buildPdf(@PathVariable Long id) throws Exception {
        return FileTools.exportPdf(investmentupRecordService.createReceptFile(id));
    }

    /**
     * 下载doc
     */
    @GetMapping("/buildword/{id}")
    @ApiOperation(value = "下载doc", notes = "传入id")
//	@PassToken
    public void buildword(@PathVariable String id, HttpServletResponse response) {
        investmentupRecordService.buildword(id, response);
    }
}
